<?

//exit;

//phpinfo(); exit; 

ini_set('zlib.output_compression', '0');		
session_start();

?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
</head>
<body><h1>Install</h1><pre>
<?

define('E', '');

require_once('_lib/_db.php');

function readyPermissions() { return true; }
function permitted() { return true; }

require_once('_lib/_lib.php');


function load_dumb($db, $dumb) {
	$sql = file_get_contents($dumb);

	$tables = array();
	$data = array();
	
	$s = strtok($sql, "\n");
	while ($s) {
		if ($s = trim($s)) {
			if (preg_match('/^INSERT INTO (\w+) \(([^)]+)\) VALUES\((.+)\);$/', $s, $r)) {		// manually detect date in url
				$table = $r[1];
				
				if (!in_array($table, $tables)) {	// new table needs to cleanup
					$db->Execute("TRUNCATE TABLE $table");
					$tables[] = $table;
				}
				
				$keys = array_trim_empty_str(explode(',', $r[2]));
				
				$val = $r[3];
				$values = array();

				while ($val !== '') {
					
					$t = '';
					if ($val{0} == "'") {	// parse string value
						$val = substr($val, 1);

						do {
							if (($pR = strpos($val, "'")) !== false) {
								$t .= substr($val, 0, $pR);
								$val = substr($val, $pR+1);
								
							} else break; // no closing quote O_o
							
							if ($val && ($val{0} == "'")) {
								$t .= "'";
								$val = substr($val, 1);
								continue;	// that was the doubled apos
							} else break;
							
						} while ($val);
						
						$values[] = str_replace('\r\n', "\n", $t);
						$val = ltrim($val);
						

						if ($val && (($val{0} == ',') || ($val{0} == ';')))			// get out comma
							$val = ltrim(substr($val, 1));

					} else {	// parse non-string value
						$pR = strpos($val, ',');
						if ($pR !== false) {		// delimited by comma
							$values[] = rtrim(substr($val, 0, $pR));
							$val = ltrim(substr($val, $pR + 1));
						} else {		// last value
							if (($pR = strpos($val, ')')) !== false) {	// end of statement
								$values[] = rtrim(substr($val, 0, $pR));
								$val = '';
							} else {	// no )
								$values[] = rtrim($val);
								$val = '';
							}
						}
					}	// end of parse single value
				}	
				
				
				$data = array();
				foreach($keys as $k => $v) 
					$data[$v] = $values[$k];

				dataset('db_insert', $table, $data);

			}
			
		}
		
		$s = strtok("\n");
	}
}



//$db->debug = true;
//print_r($db);

	
	?><h2>DB connection: Success</h2><?


//$db->Execute("UPDATE struct SET parent=412 WHERE id=413");

/*
$rec = array(
'parent' => 17, 'pos' => 4, 'attr' => 1, 'name' => 'Кэширование', 'keyword' => 'cache', 'kind' => 0, 'template' => 'admin/cache', 'tag' => 16
);

dataset('db_insert', 'struct', $rec);
*/


switch($_POST['check']) {
	
	case '258':
		if (MC)
			debug($GLOBALS['mc']->get(MC_PREFIX.'toc'));
		break;
		
	case '219':
$db->debug = true;




$_table = 'data, xdata';
$_crit =  "(data.id=xdata.id) and (data.name='body' OR data.name='anons')";
$_per_page = 20;

$d = search_safe(trim(getdata('chuck')));
$length_d = mb_strlen($d);  
//debug(mb_strlen($d));
if ( $length_d < 3 ) {
	print("<h3>Your search did not match any documents.</h3><br /><strong>Suggestions:</strong><br />Make sure all words are spelled correctly?<br />Try different keywords.<br />Try more general keywords.");	
} else {
	//$_crit2 = " AND xdata.value LIKE '%$d%'";
	//$_crit2 = " AND REGEXP_LIKE(xdata.value, '$d', 'i')";
	$_crit2 = " AND CONTAINS(xdata.filtered, '%$d%', 1) > 0";
}


if ($num = datafetch('db_item', tb($_table), $_crit.$_crit2, "COUNT(*) as num")) {

	if ($num = $num['num']) {

		$DATA['paging'] = createPaging(array(
			'num' => $num, 
			'page' => param('page'), 
			'perPage' => $_per_page,
			'pagesBefore' => 4, 'pagesAfter' => 4,
			'pagesAtStart' => 4, 'pagesAtEnd' => 4,
		));

		$DATA['body_id'] = datafetch_array('db_list', array('table' => tb($_table),
															  'where' => $_crit.$_crit2,
																'select' => 'xdata.value value, data.id id, 
															  					data.id_parent id_parent, data.assoc assoc,
																				data.name name, data.id_data id_data',
															  'index' => 'id_parent',
															  'limit' => $DATA['paging']['limit']));

	}
}

debug($num, 'num');
debug($DATA['body_id'], 'data');





//$db->Execute("SELECT xdata.value value, data.id id, data.id_parent id_parent, data.assoc assoc, data.name name, data.id_data id_data FROM data, xdata WHERE ((data.id=xdata.id) and (data.name='body' OR data.name='anons') AND CONTAINS(xdata.filtered, '%документ%', 1) > 0)");

/*
		$did = datafetch('db_insert', 'data', array('id_data' => 75, 'id_parent' => 1, 'name' => 'test data', 'value' => 'test'));
		$mid = datafetch('db_insert', 'data', array('id_data' => 76, 'id_parent' => $did, 'name' => 'test meta', 'value' => '<x>'));
		$xid = datafetch('db_insert', 'xdata', array('id' => $mid, 'value' => 'large test', 'filtered' => 'filtered text'));
		
		$d = datafetch('db_item', 'data d, data m, xdata x', "d.id=$did and m.id_parent=d.id and x.id=m.id", 'd.id id, m.id id1, x.filtered f');
debug($d);

		$d = datafetch('db_item', 'xdata x', "x.filtered is not null");
debug($d);


		dataset('db_delete', 'data', "id_data=76 and id_parent=$did");
		dataset('db_delete', 'data', "id_data=75 and id=$did");

		$d = datafetch('db_item', 'data d, data m, xdata x', "d.id=$did and m.id_parent=d.id and x.id=m.id", 'd.id id, m.id id1, x.filtered f');
debug($d);

		$d = datafetch('db_item', 'xdata x', "x.filtered is not null");
debug($d);
*/

		break;		

	case '113':

		if (isset($_FILES['dump']) && $_FILES['dump']['size']) {
		
			?><h3>loading dumb: <?=$_FILES['dump']['name']?></h3> <?
		
			load_dumb($db, $_FILES['dump']['tmp_name']);
			
			?><h3>Done.</h3> <?
			
			break;
		}

	
	case 174:
		
		set_time_limit(100);
		ini_set('output_buffering', '0');

		$total = datafetch('db_item', tb('xdata'), '1=1', 'count(id) as c');
		$total = (int)$total['c'];

print("total: $total<br>");
//$db->debug = true;

		$_frame = 500;
		$_start = ($t = (int)$_POST['chuck']) ? $t : 0;
		
//$db->debug = true;
		while(sizeof($d = datafetch_array('db_list', array('table' => tb('xdata'), 'index' => 'id', 'limit' => array($_start, $_frame))))) {
//$db->debug = false;

			set_time_limit(100);

debug(implode(', ', array_keys($d)));
			ob_flush();flush();

			foreach($d as $id => $v) {
//debug($id);
//debug(strip_tags($v['value']));
//flush();
				dataset('db_update', tb('xdata'), array('filtered' => preg_replace('/[\s\n]+/u', ' ', html_entity_decode(strip_tags($v['value']), ENT_COMPAT | ENT_HTML5,'UTF-8'))), "id=$id");
			}
				
			print(".$_start<br>");

sleep(1);
			ob_flush();flush();
sleep(1);

			$_start += $_frame;
			$_POST['chuck'] = $_start;
			
//			exit;
//			break;
		}

		
	
		
	default:	

?><form action="" enctype="multipart/form-data" method="post">
<input type="text" name="check" value=""><input type="text" name="chuck" value="<?=h($_POST['chuck'])?>"><input type="file" name="dump"><input type="submit" name="submit" value="Load dump">
</form><?
	
}
 

?>
</body>
</html>